package client;

import java.io.FileInputStream;
import java.security.KeyStore;

import javax.net.ssl.*;

/**
 * Authenticator is used to set up an authenticated connection between two
 * computers using keystores and truststores.
 * 
 * @author Victor
 */
public abstract class Authenticator {

	/**
	 * Use this to gather up the information of the users keystore and keystore.
	 * 
	 * @param password
	 *            is the password to both the keystore and the truststore
	 * @param keyStorePath
	 *            is the path relative to this program where the keystore is
	 * @param trustStorePath
	 *            is the path relative to this program where the truststore is
	 * @return the complete information of users certificates
	 * @throws Exception
	 */
	protected static SSLContext getContext(String password,
			String keyStorePath, String trustStorePath) throws Exception {
		SSLContext context;
		KeyManagerFactory keyFactory;
		KeyStore keyStore, trustStore;
		TrustManagerFactory trustFactory;
		char[] passphrase = password.toCharArray();

		context = SSLContext.getInstance("TLS");

		keyFactory = KeyManagerFactory.getInstance("SunX509");
		keyStore = KeyStore.getInstance("JKS");
		trustFactory = TrustManagerFactory.getInstance("SunX509");
		trustStore = KeyStore.getInstance("JKS");

		keyStore.load(new FileInputStream(keyStorePath), passphrase);
		keyFactory.init(keyStore, passphrase);
		trustStore.load(new FileInputStream(trustStorePath), passphrase);
		trustFactory.init(trustStore);
		context.init(keyFactory.getKeyManagers(),
				trustFactory.getTrustManagers(), null);
		return context;
	}

	public static String getGroupID(String subject) {
		String groupID = "";
		int index = subject.indexOf("OU=") + 3;
		String temp = subject.substring(index, subject.length());
		index = temp.indexOf(',');
		if (index != -1) {
			groupID = temp.substring(0, index);
		}
		return groupID;
	}

	public static String getUserID(String subject) {
		String userID = "";
		int index = subject.indexOf(',');
		if (index != -1) {
			userID = subject.substring(3, index);
		}
		return userID;
	}
}
